<?php
/**
* 数据库Session
*/
class hp_dbsession
{
	protected $model = null;
	protected $maxlifetime = 0;

	function __construct()
	{
		//$this->sessionId(); //自定义sessionid
		$this->model = G('loader')->model('dbsession');
		$this->maxlifetime = get_cfg_var('session.gc_maxlifetime');
		//垃圾回收概率设置为 1/100
		//@ini_set('session.gc_probability', 1);
		//@ini_set('session.gc_divisor', 100);
	}

	function sessionId()
	{
		if (filter_input(INPUT_GET, session_name()) == '' && filter_input(INPUT_COOKIE, session_name()) == '') {
			$id = uniqid('',true);
			session_id($id);
			return true;
		}
	}

	function open($savePath, $sessionName)
	{
		return true;
	}

	function close()
	{
		return true;
	}

	function read($sessionId)
	{
		$data = $this->model->my_table()->where('uniq', $sessionId)
			->where_more('last_time', G('timestamp'))->get_one();
		if($data) return $data['content'];
		return '';
	}

	function write($sessionId, $data)
	{
		$last_time = G('timestamp') + $this->maxlifetime;
		$this->model->my_table()->set(array(
			'uniq' => $sessionId,
			'last_time' => $last_time,
			'content' => $data,
			'is_mobile' => is_mobile()?1:0,
			'ip_address' => G('ip'),
			'last_url' => G('web.fullreuri'),
			'user_agent' => G('web.agent')
		))->insert_duplicate_key_update(array(
			'last_time' => $last_time,
			'content' => $data,
			'last_url' => G('web.fullreuri'),
		));
		return true;
	}

	function destroy($sessionId)
	{
		$this->model->my_table()->where('uniq', $sessionId)->delete();
		return true;
	}

	function gc($maxlifetime)
	{
		$this->model->my_table()->where_less('last_time', G('timestamp'))->delete();
		return true;
	}
} 

/** end **/